package com.changgou.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.apache.zookeeper.data.Id;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zero
 * @date 2020/7/1
 */

//声明是一个canal的监听类
@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 声明一个监听方法
     * @param eventType
     * @param rowData
     */
    @ListenPoint(schema = "changgou_goods",table = "tb_spu")
    public void goodsUp(CanalEntry.EventType eventType , CanalEntry.RowData rowData){
        //获取改变之前的数据,并封装到map集合中
        Map<String,String> oldData = new HashMap<>();
        rowData.getBeforeColumnsList().forEach(c -> oldData.put(c.getName(),c.getValue()) );
        //获取改变之前的数据
        Map<String,String> newData = new HashMap<>();
        rowData.getAfterColumnsList().forEach(c -> newData.put(c.getName(),c.getValue()) );

        //获取最新上架的商品 is_marketable 0->1
        if ("0".equals(oldData.get("is_marketable")) && "1".equals(newData.get("is_marketable"))){
            //找到匹配的商品数据,将商品的spuId发送到消息队列中
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",newData.get("id"));
        }

        //获取最新下架的商品 1->0
        if ("1".equals(oldData.get("is_marketable")) && "0".equals(newData.get("is_marketable"))){
            //将商品的spuid发送到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",newData.get("id"));
        }

        //获取最新审核的商品 status 0 -> 1
        if ("0".equals(oldData.get("status")) && "1".equals(newData.get("status"))){
            //将商品的spuid发送到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_AUDIT_EXCHANGE,"",newData.get("id"));
            System.out.println(newData.get("id"));
        }
    }


}
